package com.sdy.healthcode.biz.dto;

import com.sdy.common.utils.StringUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Data
@ApiModel(value = "地址")
@Accessors(chain = true)
public class Address {
    @ApiModelProperty(value = "省市", required = true)
    private String area;
    @ApiModelProperty(value = "详细地址", required = true)
    private String addr;

    @ApiModelProperty(value = "省CODE")
    private String regionProvince;
    @ApiModelProperty(value = "市CODE")
    private String regionCity;
    @ApiModelProperty(value = "区CODE")
    private String regionArea;
    @ApiModelProperty(value = "街道CODE")
    private String regionStreet;
    @ApiModelProperty(value = "社区")
    private String regionCommunity;
    
    public static final String SPLITTER_1 = "##";
    public static final String SPLITTER_2 = "@@";

    public static List<Address> fromStr(String s) {
        if (s == null) {
            return Collections.emptyList();
        }
        List<Address> r = new ArrayList<>();
        for (String s1 : s.split(SPLITTER_1)) {
            if (StringUtil.isBlank(s1)) {
                continue;
            }
            Address address = new Address();
            String[] s2 = s1.split(SPLITTER_2);
            address.setArea(s2[0]);
            address.setAddr(s2.length >=2 ? s2[1] : "");
            r.add(address);
        }
        return r;
    }

    public static Address fromStrToSingleAddr(String s) {
        List<Address> l = fromStr(s);
        return l.isEmpty() ? null : l.get(0);
    }
    
    public static List<Address> fromCodeStr(String s) {
        if (s == null) {
            return Collections.emptyList();
        }
        List<Address> r = new ArrayList<>();
        for (String s1 : s.split(SPLITTER_1)) {
            if (StringUtil.isBlank(s1)) {
                continue;
            }
            Address address = new Address();
            String[] s2 = s1.split(SPLITTER_2);
            int len = s2.length;
            address.setRegionProvince(len >= 1 ? s2[0] : null);
            address.setRegionCity(len >= 2 ? s2[1] : null);
            address.setRegionArea(len >= 3 ? s2[2] : null);
            address.setRegionStreet(len >= 4 ? s2[3] : null);
            address.setRegionCommunity(len >= 5 ? s2[4] : null);
            r.add(address);
        }
        return r;
    }

    public static Address fromCodeStrToSingleAddr(String s) {
        List<Address> l = fromCodeStr(s);
        return l.isEmpty() ? null : l.get(0);
    }

    @Override
    public String toString() {
        return area + SPLITTER_2 + addr;
    }

    public static String toStr(List<Address> addressList) {
        return addressList.stream().map(Address::toString).collect(Collectors.joining(SPLITTER_1));
    }
}
